package com.softline.documentsmall.service.impl;

import com.softline.documentsmall.dao.EntryDetailMapper;
import com.softline.documentsmall.dao.EntryDetailSubmitMapper;
import com.softline.documentsmall.entity.DetailSubmitPageQueryVo;
import com.softline.documentsmall.entity.EntryDetails;
import com.softline.documentsmall.entity.EntryDetailsPageResp;
import com.softline.documentsmall.entity.EntryDetailsSubmit;
import com.softline.documentsmall.ret.BusinessErrorEnum;
import com.softline.documentsmall.ret.ReturnVO;
import com.softline.documentsmall.ret.ReturnVOUtils;
import com.softline.documentsmall.service.EntryDetailLogService;
import com.softline.documentsmall.service.EntryDetailService;
import com.softline.documentsmall.service.EntryDetailsSubmitService;
import com.softline.documentsmall.utils.VoTransferUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 条目提交历史service实现类
 *
 * @author zhongweicheng
 * @date 2020/9/4 16:26
 */

@Service
@Slf4j
public class EntryDetailsSubmitServiceImp implements EntryDetailsSubmitService {

    @Autowired
    EntryDetailSubmitMapper entryDetailSubmitMapper;

    @Autowired
    EntryDetailService entryDetailService;

    @Autowired
    EntryDetailMapper detailMapper;

    @Autowired
    EntryDetailLogService entryDetailsLogService;

    @Value(value = "${pageParams.currPage}")
    private Integer currPageCfg;

    @Value(value = "${pageParams.pageSize}")
    private Integer pageSizeCfg;

    @Override
    public ReturnVO findByParams(EntryDetailsSubmit entryDetailsSubmit) {
        try {
            return ReturnVOUtils.success(entryDetailSubmitMapper.findByParams(entryDetailsSubmit, (currPageCfg - 1) * pageSizeCfg, pageSizeCfg));
        } catch (Exception e) {
            log.warn("EntryDetailsSubmitServiceImp findByParams exception:{} ", e.getMessage());
        }
        return ReturnVOUtils.businessFail(BusinessErrorEnum.FAIL);
    }

    @Override
    public ReturnVO adminUpdateById(EntryDetailsSubmit entryDetailsSubmit) {
        if (Objects.nonNull(entryDetailsSubmit)) {
            if (entryDetailsSubmit.getId() != null) {
                //调用更新mapper
                entryDetailSubmitMapper.adminUpdateEntryDetailSubmitById(entryDetailsSubmit);
                return ReturnVOUtils.success();
            } else {
                log.warn("EntryDetailsSubmitServiceImp adminUpdateById id is null!");
                return ReturnVOUtils.businessFail(BusinessErrorEnum.ID_IS_NULL);
            }
        } else {
            return ReturnVOUtils.businessFail(BusinessErrorEnum.PARAMS_HAS_NULL);
        }
    }

    @Override
    public ReturnVO userUpdateById(EntryDetailsSubmit entryDetailsSubmit) {
        if (Objects.nonNull(entryDetailsSubmit)) {
            if (entryDetailsSubmit.getId() != null) {
                //调用更新mapper
                entryDetailSubmitMapper.userUpdateEntryDetailSumbitById(entryDetailsSubmit);
                //根据id查出来
                EntryDetailsSubmit submit = this.findById(entryDetailsSubmit.getId());
                //调用新增接口，将记录保存到entry_detail主表,vo转换
                EntryDetails details = (EntryDetails) VoTransferUtils.transferVo(submit);
                entryDetailService.insertEntryDetails(details);
                return ReturnVOUtils.success();
            } else {
                log.warn("EntryDetailsSubmitServiceImp userUpdateById id is null!");
                return ReturnVOUtils.businessFail(BusinessErrorEnum.ID_IS_NULL);
            }
        } else {
            return ReturnVOUtils.businessFail(BusinessErrorEnum.PARAMS_HAS_NULL);
        }
    }

    @Override
    public ReturnVO insertEntryDetailsSubmit(List<EntryDetailsSubmit> entryDetailsSubmits) {
        //数据库针对于每一个释义模块都是一行记录
        if (Objects.nonNull(entryDetailsSubmits) && entryDetailsSubmits.size() != 0) {
            //循环集合插入多条记录
            entryDetailsSubmits.stream().forEach(r -> {
                if (Objects.nonNull(r)) {
                    entryDetailSubmitMapper.insertEntryDetailSumbit(r);
                } else {
                    log.warn("EntryDetailsSubmitServiceImp insertEntryDetailsSubmit stream has null");
                }
            });
        } else {
            return ReturnVOUtils.businessFail(BusinessErrorEnum.PARAMS_HAS_NULL);
        }
        return ReturnVOUtils.success();
    }

    @Override
    public ReturnVO softDeleteById(Integer id) {
        try {
            entryDetailSubmitMapper.softDeleteEntryDetailSumbitById(id);
            return ReturnVOUtils.success();
        } catch (Exception e) {
            log.warn("EntryDetailsSubmitServiceImp softDeleteById exception:{}", e.getMessage());
        }
        return ReturnVOUtils.businessFail(BusinessErrorEnum.FAIL);
    }

    /**
     * 查看审批状态 根据id
     *
     * @param id
     * @return
     */
    @Override
    public boolean isApproveState(Integer id) {

        boolean flag = false;
        Integer ids = entryDetailSubmitMapper.findApproveStateById(id);
        //0 未审批 1 审批通过 2 审批不通过
        if (Objects.nonNull(ids) && id != 0) {
            flag = true;
        }
        return flag;
    }

    /**
     * 根据dictionaryId,language,title查询条目历史记录
     *
     * @param dictionaryId
     * @param language
     * @param title
     * @return
     */
    @Override
    public EntryDetailsSubmit findByDictionaryIdLanguageTitle(Integer dictionaryId, String language, String title) {
        EntryDetailsSubmit entryDetailsSubmit = null;
        if (Objects.nonNull(dictionaryId) && Objects.nonNull(language) && Objects.nonNull(title)) {
            entryDetailsSubmit = entryDetailSubmitMapper.findByDictionaryIdLanguageTitle(dictionaryId, language, title);
        } else {
            log.info("EntryDetailsSubmitServiceImp findByDictionaryIdLanguageTitle params has null!");
        }
        return entryDetailsSubmit;
    }

    /**
     * 按照查询条目历史
     *
     * @param id
     * @return
     */
    @Override
    public EntryDetailsSubmit findById(Integer id) {
        return entryDetailSubmitMapper.findById(id);
    }

    @Override
    public String editDictionaryBlock(EntryDetailsSubmit submit) {
        //dictionaryId language sort approveState为0 有记录 则不能插入
        EntryDetailsSubmit submit1 = entryDetailSubmitMapper.isApproveInsert(submit.getDictionaryId(), submit.getLanguage(), submit.getSort());
        if (submit1 != null) {
            return "有未审批状态，暂不允许该操作!";
        }
        //插入记录
        try {
            //生成submit的UUID
            String uuid = UUID.randomUUID().toString();
            submit.setSubmitId(uuid);
            entryDetailSubmitMapper.insertEntryDetailSumbit(submit);
        } catch (Exception e) {
            return "操作异常!" + e.getMessage();
        }
        return "操作成功,待管理员审核!";
    }

    /**
     * 管理员审核
     *
     * @return 1, 1, xiaowu, 666
     */
    @Override
    public String adminApproveSubmit(Integer id, Integer approveState, String userName, String userId, String reason) {
        String value = "success";
        //获取数据库的记录
        EntryDetailsSubmit submit = findById(id);
        if (submit == null) {
            value = "未找到找该ID的记录";
        } else {
            //如果状态已经是 1 或者 2 则表示之前已被审核过，不允许再次审核
            Integer state = submit.getApproveState();
            if (state == 1 || state == 2) {
                value = "该记录之前已被审核,不允许再次审核操作!";
            } else {
                //更新submit表
                try {
                    entryDetailSubmitMapper.updateApproveStateById(id, approveState);
                } catch (Exception e) {
                    log.error("exception updateSubmitRecord!:{}", e.getMessage());
                    value = "error";
                }
                //如果approveState为1表示通过，需要将title和content更新到主表
                if (approveState == 1) {
                    //is_create 为0 更新，为1 新增
                    if (submit.getIsCreate() == 0) {
                        //根据 sort language dictionaryId 更新detail的title content字段
                        try {
                            //调用日志接口,新增日志
                            entryDetailsLogService.insertDetailsLog(submit, 1, userName, userId,reason);
                            detailMapper.updateTitleContentByDicidLanguageAndSort(submit.getDictionaryId(), submit.getLanguage(), submit.getSort(), submit.getTitle(), submit.getContent());

                        } catch (Exception e) {
                            log.error("exception updateDetailRecord!:{}", e.getMessage());
                            value = "error";
                        }
                    } else {
                        EntryDetails details = new EntryDetails();
                        details.setContent(submit.getContent());
                        details.setDictionaryId(submit.getDictionaryId());
                        details.setLanguage(submit.getLanguage());
                        details.setTitle(submit.getTitle());
                        details.setSort(submit.getSort());
                        try {
                            //调用日志接口,新增日志
                            entryDetailsLogService.insertDetailsLog(submit, 2, userName, userId,reason);
                            //插入
                            entryDetailService.insertEntryDetails(details);

                        } catch (Exception e) {
                            log.error("exception insertDetailRecord!:{}", e.getMessage());
                            value = "error";
                        }

                    }
                }
            }
        }

        return value;

    }

    @Override
    public ReturnVO getDetailSubmitByPage(DetailSubmitPageQueryVo vo) {
       if(vo == null){
           return ReturnVOUtils.success("参数为空");
       }else{
           if(vo.getStartTime() != null && !vo.getStartTime().trim().equalsIgnoreCase("")){
               vo.setStartTime(vo.getStartTime()+" 00:00:00");
           }
           if(vo.getEndTime() != null && !vo.getEndTime().trim().equalsIgnoreCase("")){
               vo.setEndTime(vo.getEndTime()+" 23:59:59");
           }

           vo.setPage((vo.getPage()-1)*vo.getSize());
           List<EntryDetailsSubmit> submits = entryDetailSubmitMapper.getByPage(vo);
          Long count = entryDetailSubmitMapper.getPageTotalCount(vo);
           EntryDetailsPageResp resp =  new EntryDetailsPageResp();
           resp.setList(submits);
           resp.setTotal(count);
           return ReturnVOUtils.success(resp);
       }
    }
}
